/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/buddy-strings
   @Language: C++
   @Datetime: 19-05-28 11:30
   */


class Solution {
public:
	/**
	 * @param A: string A
	 * @param B: string B
	 * @return: bool
	 */
	bool buddyStrings(string &A, string &B) {
		// Write your code here
		if(A.length()!=B.length())  return false;
		if(A.compare(B)==0){
			unordered_set<char> s;
			for(int i=A.length(); i--; s.insert(A[i]))
				if(s.count(A[i])) return true;
			return false;
		}
		int i=0, j=0;
		for(i=0; i<A.length() && A[i]==B[i]; ++i);
		for(j=i+1; j<A.length() && A[j]==B[j]; ++j);
		if(i==A.length() || j==A.length()) return false;
		swap(A[i],A[j]);
		return A.compare(B)==0;
	}
};
